function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}


function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
  formatTime: formatTime
}

const app = getApp()
let requestNum = 0;

// 拼接POST请求参数
function json2Form(json) {
  var str = [];
  for (var p in json) {
    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
  }
  return str.join("&");
}

//网络请求old甜街版本封装
function request(urlStr = "", parameters = "", success, method = "GET", header = {
  'content-type': 'application/json'
}) {
  wx.request({
    url: app.globalData.BaseURL + urlStr + (method == "GET" ? "?" : "") + parameters,
    data: {
      'access_token': '6213ede986414d5fae5226304aeba411'
    },
    method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: header ? header : "application/json", // 设置请求的 header
    success: function(res) {
      console.log(res);
      success(res);
    },
    fail: function() {
      // fail
      wx.hideToast();
    },
    complete: function() {
      // complete
      wx.hideToast();
    }
  })
}
const getRequest = (url, data, success) => {
  wx.showToast({
    title: "加载中",
    mask: true,
    icon: "loading",
    duration: 60000
  });
  requestNum++;
  console.log(requestNum, "requestNum++");
  wx.request({
    url: app.globalData.BaseURL + url,
    data: data,
    method: "GET",
    header: {
      "Content-Type": "application/x-www-form-urlencoded",
      // "Content-Type": "application/json;charset=utf-8",
      "userViewId": app.globalData.viewId,
    },
    success: res => {
      requestNum--;
      console.log(requestNum, "requestNum--");
      if (requestNum == 0) {
        wx.hideToast();
      }
      if (res.data.code == 200) {
        success(res);
      } else if (res.data.code == 600) {
        // wx.hideToast();
        wx.navigateTo({
          url: "/pages/login/login"
        })
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 2000
        })
        if (requestNum) { //如果还有其他请求没有结束，仍然loading
          wx.showToast({
            title: "加载中",
            mask: true,
            icon: "loading",
            duration: 60000
          });
        }
      }
    },
    fail: res => {
      requestNum--;
      wx.hideToast();
      wx.showToast({
        title: '网络请求错误！',
        icon: 'none',
        duration: 2000
      })
    },
  })
}
const postRequest = (url, data, success, headerFlag) => {
  wx.showToast({
    title: "加载中",
    mask: true,
    icon: "loading",
    duration: 60000
  }); 
  requestNum++; 
  wx.request({
    url: app.globalData.BaseURL + url,
    data: data,
    method: "POST",
    header: {
      "Content-Type": headerFlag ? "application/json;charset=utf-8" : "application/x-www-form-urlencoded",
      "userViewId": app.globalData.viewId,
    },
    success: res => {
      requestNum--;
      if (res.data.code == 200) {
        success(res);
        wx.hideToast();
      } else if (res.data.code == 600) { //未登录
        wx.hideToast();
        wx.navigateTo({
          url: "/pages/login/login"
        })
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 2000
        })
        if (requestNum) { //如果还有其他请求没有结束，仍然loading
          wx.showToast({
            title: "加载中",
            mask: true,
            icon: "loading",
            duration: 60000
          });
        }
      }
    },
    fail: res => {
      requestNum--;
      wx.showToast({
        title: '网络请求错误！',
        icon: 'none',
        duration: 2000
      })
    }
  })
}
//HUD 
//成功提示
function showSuccess(title = "成功啦", duration = 2500) {
  wx.showToast({
    title: title,
    icon: 'success',
    duration: (duration <= 0) ? 2500 : duration
  });
}
//loading提示
function showLoading(title = "请稍后", duration = 5000) {
  wx.showToast({
    title: title,
    icon: 'loading',
    mask: true,
    duration: (duration <= 0) ? 5000 : duration
  });
}
// 错误提示
function showErrorTost() {
  that.$wuxToast.show({
    type: 'text',
    timer: 1500,
    color: '#fff',
    text: '请求错误',
    success: () => console.log('请求错误')
  })
}
//隐藏提示框
function hideToast() {
  wx.hideToast();
}

const getUserPhone = (e,success) => {
  let type = e.currentTarget.dataset.type;
  if (e.detail.errMsg === "getPhoneNumber:ok") { //用户同意授权
    console.log("用户同意授权");
    getRequest('/api/wx/bindPhone',{
      openId: app.globalData.openId,
      sessionKey: app.globalData.sessionKey,
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv
    },res => { 
      wx.showToast({
        title: res.data.msg,
      }) 
      app.globalData.viewId = res.data.data.viewId;
      app.globalData.phone = res.data.data.phone;
      console.log(app.globalData.phone, "app.globalData.phone===")
      success(res);
    })
  }
}
//显示带取消按钮的消息提示框
function alertViewWithCancel(title = "提示", content = "消息提示", confirm, showCancel = "true") {
  wx.showModal({
    title: title,
    content: content,
    showCancel: showCancel,
    success: function(res) {
      if (res.confirm) {
        confirm();
      }
    }
  });
}
//显示不取消按钮的消息提示框
function alertView(title = "提示", content = "消息提示", confirm) {
  alertViewWithCancel(title, content, confirm, false);
}

function checkOpenId(that) {
  /*
   * 若openId为空，则重新获取openId
   */
  if (app.globalData.openId == "") {
    // 微信登录，获取openId
    wx.login({
      success: function(wxRes) {
        console.log("登陆成功");
        console.log(wxRes);
        // 获取openid
        // wx.request({
        //   url: app.globalData.BaseURL + '/api/wx/login' + "?code=" + wxRes,
        //   method: 'GET',
        //   header: {
        //     "Content-Type": "application/x-www-form-urlencoded"
        //   },
        //   data: {
        //     'code': wxRes.code,
        //     'xcxid': app.globalData.xcxidStr
        //   },
        //   success: function(res) {
        //     var openId = res.data.data;
        //     console.log("openId===" + openId);
        //     app.globalData.openId = openId;
        //   },
        //   fail: function(res) {
        //     console.log("失败");
        //     app.globalData.openId = "";
        //     that.$wuxToast.show({
        //       type: 'text',
        //       timer: 1500,
        //       color: '#fff',
        //       text: '获取微信登录失败，请退出重试',
        //       success: () => console.log('获取微信登录失败，请退出重试')
        //     })
        //   }
        // })
      },
      fail: function() {
        console.log("登录失败");
        that.$wuxToast.show({
          type: 'text',
          timer: 1500,
          color: '#fff',
          text: '微信登录失败，请退出重试',
          success: () => console.log('微信登录失败，请退出重试')
        })
      }
    });
  }
}


var countdown = 60;
// 倒计时
function settime(that) {
  if (countdown == 0) {
    that.setData({
      codeStr: '重新获取验证码',
      codeCanTouch: true
    })
    countdown = 60;
    return;
  } else {
    that.setData({
      codeStr: countdown + 's后重新获取',
      codeCanTouch: false
    })

    countdown--;
  }
  setTimeout(function() {
    settime(that)
  }, 1000)
}

/* 手机号验证 */
function validatePhone(phone) {
  var mbTest = /^(1)[0-9]{10}$/;
  if (!mbTest.test(phone)) {
    return "请输入正确手机号";
  }
  return "";
}

//paraName 等找参数的名称
function getUrlParam(url, paraName) {
  console.log('util的url=====' + url);
  console.log('util的paraName=====' + paraName);


  var arrObj = url.split("?");
  if (arrObj.length > 1) {
    var arrPara = arrObj[1].split("&");
    var arr;
    for (var i = 0; i < arrPara.length; i++) {
      arr = arrPara[i].split("=");
      if (arr != null && arr[0] == paraName) {
        return arr[1];
      }
    }
    return "";
  } else {
    return "";
  }
}

/**
 * 比较版本号
 */
function versionfunegt(ver1, ver2) {
  var version1pre = parseFloat(ver1);
  var version2pre = parseFloat(ver2);
  var version1next = ver1.replace(version1pre + ".", "");
  var version2next = ver2.replace(version2pre + ".", "");
  if (version1pre > version2pre) {
    return true;
  } else if (version1pre < version2pre) {
    return false;
  } else {
    if (version1next >= version2next) {
      return true;
    } else {
      return false;
    }
  }
}

module.exports = {
  formatTime: formatTime,
  json2Form: json2Form,
  request: request,
  showSuccess: showSuccess,
  showLoading: showLoading,
  hideToast: hideToast,
  alertViewWithCancel: alertViewWithCancel,
  alertView: alertView,
  checkOpenId: checkOpenId,
  settime: settime,
  validatePhone: validatePhone,
  getUrlParam: getUrlParam,
  versionfunegt: versionfunegt,
  getRequest: getRequest,
  postRequest: postRequest,
  getUserPhone: getUserPhone
}